<template>
  <div class="announcement-form">
    <h2>{{ isEdit ? '编辑公告' : '添加公告' }}</h2>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="form-container"
    >
      <el-form-item label="所属社团" prop="clubId">
        <el-select v-model="form.clubId" placeholder="请选择社团" filterable clearable
                  :disabled="isEdit && !isAdmin">
          <el-option
            v-for="club in clubOptions"
            :key="club.id"
            :label="club.name"
            :value="club.id"
          ></el-option>
        </el-select>
        <div class="form-tip">不选择社团则发布为学校公告</div>
      </el-form-item>
      
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入公告标题"></el-input>
      </el-form-item>
      
      <el-form-item label="公告内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="10"
          placeholder="请输入公告内容"
        ></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAnnouncementDetail, addAnnouncement, updateAnnouncement } from '@/api/announcement'
import { getClubList } from '@/api/club'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref(null)
const clubOptions = ref([])

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')
const isClubLeader = computed(() => userInfo.value.role === 'club_leader')

// 是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const form = reactive({
  clubId: null,
  title: '',
  content: ''
})

// 表单校验规则
const rules = reactive({
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 255, message: '公告标题不能超过255个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ]
})

// 加载社团列表
const loadClubs = async () => {
  try {
    let params = { pageSize: 1000 }
    
    // 如果是社团负责人且不是管理员，只能看到自己管理的社团
    if (isClubLeader.value && !isAdmin.value) {
      params.leaderId = userInfo.value.id
    }
    
    const res = await getClubList(params)
    if (res.data && res.code === 200) {
      clubOptions.value = res.data.list
      
      // 如果是社团负责人且不是管理员，默认选择第一个社团
      if (!isEdit.value && isClubLeader.value && !isAdmin.value && clubOptions.value.length > 0) {
        form.clubId = clubOptions.value[0].id
      }
    } else {
      ElMessage.error(res.message || '获取社团列表失败')
    }
  } catch (error) {
    console.error('获取社团列表出错:', error)
    ElMessage.error('获取社团列表失败')
  }
}

// 获取公告详情
const getAnnouncementInfo = async (id) => {
  try {
    const res = await getAnnouncementDetail(id)
    if (res.code === 200 && res.data) {
      // 填充表单数据
      form.clubId = res.data.clubId
      form.title = res.data.title
      form.content = res.data.content
      
      // 检查权限
      if (isClubLeader.value && !isAdmin.value) {
        
        // 检查是否是该社团的负责人
        if (res.data.clubId) {
          console.log("clubOptions:",clubOptions)
          console.log(res.data.clubId)
          console.log(userInfo.value.id)
          let isLeader = clubOptions.value.some(club => 
            club.id === res.data.clubId && club.leaderId === userInfo.value.id
          )
              
          if (!isLeader) {
            ElMessage.error('您无权编辑此公告')
            goBack()
          }
        } else {
          // 不是社团公告，无权编辑
          ElMessage.error('您无权编辑学校公告')
          goBack()
        }
      }
    } else {
      ElMessage.error(res.message || '获取公告信息失败')
      goBack()
    }
  } catch (error) {
    console.error('获取公告详情出错:', error)
    ElMessage.error('获取公告信息失败')
    goBack()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 如果是社团负责人但非管理员，确保只能创建自己社团的公告
    if (isClubLeader.value && !isAdmin.value) {
      if (!form.clubId) {
        ElMessage.error('社团负责人不能创建学校公告')
        return
      }
      
      const isLeader = clubOptions.value.some(club => 
        club.id === form.clubId && club.leaderId === userInfo.value.id
      )
      if (!isLeader) {
        ElMessage.error('您无权为此社团创建公告')
        return
      }
    }
    
    if (isEdit.value) {
      // 编辑公告
      const id = route.params.id
      const res = await updateAnnouncement(id, form)
      if (res.code === 200) {
        ElMessage.success('更新成功')
        goBack()
      } else {
        ElMessage.error(res.message || '更新失败')
      }
    } else {
      // 添加公告
      const res = await addAnnouncement(form)
      if (res.code === 200) {
        ElMessage.success('添加成功')
        goBack()
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('表单数据不完整或格式不正确')
  }
}

// 返回上一页
const goBack = () => {
  router.push('/announcements')
}

// 初始化
onMounted(async() => {
  await loadClubs()
  
  if (isEdit.value && route.params.id) {
   await getAnnouncementInfo(route.params.id)
  }
})
</script>

<style scoped>
.announcement-form {
  padding: 20px;
}

.form-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style> 